/**
 * 封装Music类
 *  this指向问题
 *     构造函数中this  实例对象
 *     原型方法中this  实例对象
 *     对象方法中this  实例对象
 *     普通方法this    window
 *     事件方法this   事件对象
 * 
 *     箭头函数中没有this, this表示外层对象
 */
class Music {
    constructor(parentNode) {
        this.ulEle = document.querySelector(parentNode);
        this.currentIndex = 0; // 正在播放的音乐序号
        this.play = false;
        // let that = this;

        this.ulEle.addEventListener('click', () => {
            let e = event || window.event;
            let target = e.target || e.srcElement;

            if (target.nodeName == 'IMG') {
                let index = this.getIndex(target);

                //相同表示同一首音乐状态的切换
                if (index == this.currentIndex) {
                    this.playAndPause(target);
                } else {
                    this.pausePrevMusic();
                    this.playMusic(target);
                    this.currentIndex = index;
                }
            }
        });
    }

    /**
     * 获取点击按钮序号
     */
    getIndex(target) {
        let liEle = target.parentElement.parentElement.parentElement;
        return liEle.id;
    }

    /**
     * 播放暂停状态切换
     */
    playAndPause(target) {
        if (this.play) {
            this.pauseMusic(target);
        } else {
            this.playMusic(target);
        }
    }
    /**
     * 暂停上一个播放音乐
     */
    pausePrevMusic() {
        if(this.currentIndex == 0){
            return;
        }
        let currentLiEle = document.getElementById(this.currentIndex);
        let currentImgEle = currentLiEle.lastElementChild.lastElementChild.firstElementChild;
        this.play = false;
        currentImgEle.src = './image/pause.png';
    }
    /**
     * 音乐暂停
     */
    pauseMusic(target) {
        this.play = false;
        target.src = './image/pause.png'
    }
    /**
     * 播放音乐
     */
    playMusic(target) {
        this.play = true;
        target.src = './image/play.png'
    }
}